package com.projet.whattowatch.activity;

import com.projet.whattowatch.R;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;

public class SearchCinemaFragment extends Fragment {
	private EditText keyword;
	private Button searchButton;
	private ListView searchList;
	
	final String EXTRA_CINEMA_NAME = "cinema_name";

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
	{
		View rootView = inflater.inflate(R.layout.search_cinema_layout,
				container, false);

		keyword = (EditText) rootView.findViewById(R.id.keywordEditText);
		searchButton = (Button) rootView.findViewById(R.id.searchButton);
		searchList = (ListView) rootView.findViewById(R.id.searchListView);

		searchButton = (Button) rootView.findViewById(R.id.searchButton);
		searchButton.setOnClickListener(searchListener);
		
		searchList.setOnItemClickListener(new OnItemClickListener()
		{
		    
		    @Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id)
		    { 
		    	String cinemaName = searchList.getItemAtPosition(position).toString();
		    	
		    	Intent cinemaDetail = new Intent(getActivity().getApplicationContext(), CinemaDetailActivity.class);
		    	cinemaDetail.putExtra(EXTRA_CINEMA_NAME, cinemaName);
		    	startActivity(cinemaDetail);
		     
		    }
		 });

		return rootView;
	}

	public OnClickListener searchListener = new OnClickListener() {
		@Override
		public void onClick(View arg0) {
			String stringKeyword = keyword.getText().toString();

			ArrayAdapter<String> adapter = new ArrayAdapter<String>(
					getActivity().getApplicationContext(),
					R.layout.custom_textview,
					MainActivity.mLibCinema.searchCinema(stringKeyword));

			searchList.setAdapter(adapter);
			hideSoftKeyboard();
		}
	};
	
	private void hideSoftKeyboard()
    {
        if(getActivity().getCurrentFocus()!=null && getActivity().getCurrentFocus() instanceof EditText){
            InputMethodManager imm = (InputMethodManager)getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(getActivity().getWindow().getCurrentFocus().getWindowToken(), 0);
        }
    }
}
